import { ElMessageBox } from 'element-plus'

/**
 * 初始化文档流样式缩放比例
 * tips：
 * 1.适用于不包含element-plus弹出类组件的项目，弹出类组件包括但不限于
 *    - 日期选择
 *    - 下拉列表
 *    - Autocomplete
 *    - Tooltip
 *    - Popover
 * @returns
 */
const initDocumentBodyStyleZoom = () => {
  let ratio = 0
  const screen: any = window.screen
  const ua = navigator.userAgent.toLowerCase()
  const style: any = document.body.style
  if (window.devicePixelRatio !== undefined) {
    ratio = window.devicePixelRatio
  } else if (~ua.indexOf('msie')) {
    if (screen.deviceXDPI && screen.logicalXDPI) {
      ratio = screen.deviceXDPI / screen.logicalXDPI
    }
  } else if (window.outerWidth !== undefined && window.innerWidth !== undefined) {
    ratio = window.outerWidth / window.innerWidth
  }
  if (ratio) {
    ratio = Math.round(ratio * 100)
  } else {
    ratio = 100
  }
  style.zoom = 100 / ratio
}

/**
 * 缩放提醒
 * 如果存在系统级缩放，则会提示用户将浏览器缩放到适当的比例
 * @returns
 */
const zoomTips = () => {
  // 如果是IE，直接返回
  const ua = navigator.userAgent.toLowerCase()
  if (~ua.indexOf('msie')) {
    return
  }

  // 计算系统缩放
  let ratio = 0
  let broRatio = 1
  if (window.devicePixelRatio !== undefined) {
    ratio = window.devicePixelRatio
    // 如果缩放为1，直接返回
    if (ratio === 1) {
      return
    }
  }
  if (window.outerWidth !== undefined && window.innerWidth !== undefined) {
    broRatio = window.outerWidth / window.innerWidth
  }

  const sysRatio = Math.round((ratio / broRatio) * 100)

  // 未正确获取到系统缩放，直接返回
  if (!sysRatio) {
    return
  }

  // 计算需要浏览器调整到的缩放比例
  const zoom = 100 / sysRatio
  const ignoreZoomTips = localStorage.getItem('ignore-zoom-tips')

  // 如果需要浏览器调整，并且用户未忽略该提示信息，则提示
  if (Math.abs(1 - zoom) > 0.05 && !ignoreZoomTips) {
    ElMessageBox.confirm(`请把浏览器缩放比例调整至${(zoom * 100).toFixed()}%附近，以达到最好的显示效果！`, '提示', {
      confirmButtonText: '忽略',
      cancelButtonText: '关闭',
      type: 'warning'
    }).then(() => {
      localStorage.setItem('ignore-zoom-tips', `${new Date().getTime()}`)
    })
  }
}

/**
 * 节流函数
 * @param fn 目标函数
 * @param delay 延迟时间
 * @returns 节流后函数
 */
const throttle = (fn: (...args: any) => void, delay = 600) => {
  let lastExecutionTime = 0
  return (...args: any) => {
    const currentTime = Date.now()
    if (currentTime - lastExecutionTime > delay) {
      fn(...args)
      lastExecutionTime = currentTime
    }
  }
}

export { initDocumentBodyStyleZoom, zoomTips, throttle }
